package com.yulintu.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.util.Set;

/**
 * json解析
 * Created by caomin on 2017/10/12.
 */

@Component
public class FileUploadUtils {


     @Autowired
     JdbcTemplate jdbcTemplate;



    public void writeFile(String path,InputStream inputStream) throws IOException {


    }

    //// TODO: 2017/10/12 根据传递过来的tableNAME和record，将文件存放到该目录下。并且更新tb_file这个表中附件的目录位置

    public  String  save(String json,String tableName){
        JSONObject jsonObject = JSONObject.parseObject(json);
        String columnKey = getColumnKey(jsonObject);
        String columnValue = getColumnValue(jsonObject);
        columnKey+=") ";
        columnValue+=")";
        String sql="INSERT INTO "+tableName+columnKey +"values"+columnValue;
        jdbcTemplate.batchUpdate(sql);
        return (String) jsonObject.getOrDefault("id",null);
    }


    private String getColumnValue(JSONObject jo) {
        StringBuffer sb=new StringBuffer(" (");
        Set<String> keys = jo.keySet();
        for (String key : keys) {
            Object obj = jo.get(key);
            if (obj instanceof JSONObject) {
                getColumnValue((JSONObject) obj);
            } else if (obj instanceof JSONArray) {
                JSONArray array  =(JSONArray)obj;
                for (int i=0;i<array.size();i++){
                    JSONObject jboj=array.getJSONObject(i);
                    getColumnValue(jboj);
                }
            } else {

                sb.append(jo.getString(key)+",");
            }
        }
        return sb.substring(0,sb.length()-1).toString();
    }
    private String getColumnKey(JSONObject jo) {
        StringBuffer sb=new StringBuffer(" (");
        Set<String> keys = jo.keySet();
        for (String key : keys) {
            Object obj = jo.get(key);
            if (obj instanceof JSONObject) {
                getColumnKey((JSONObject) obj);
            } else if (obj instanceof JSONArray) {
                JSONArray array  =(JSONArray)obj;
                for (int i=0;i<array.size();i++){
                    JSONObject jboj=array.getJSONObject(i);
                    getColumnKey(jboj);
                }
            } else {
                sb.append(key+",");
            }
        }
        return sb.substring(0,sb.length()-1).toString();
    }
}
